<script lang="ts" setup>
import { getPatientConsultOrderPreAPI, postPatientConsultOrderAPI } from '@/apis/consult';
import { getPatientInfoByIdAPI } from '@/apis/patient'
import { useConsultStore } from '@/stores/counter';
import type { GetPatientConsultOrderPreData } from '@/types/consult';
import type { GetPatientMylistItem } from '@/types/patient';
import { onMounted, ref } from 'vue';


//
// 获取问诊参数 store
const store = useConsultStore()


//1.获取就诊订单信息和抵扣信息
const orderPreInfo = ref<GetPatientConsultOrderPreData>()
const getOrderPre = async ()=>{
  const res = await getPatientConsultOrderPreAPI({
    type:store.type,
    illnessType:store.illnessType,
  })
  orderPreInfo.value = res.data
}
getOrderPre()

//2.获取患者信息
const patientInfo = ref<GetPatientMylistItem>()
  const getPatientInfo= async ()=>{
    const res = await getPatientInfoByIdAPI(store.patientId)
      patientInfo.value = res.data
    }
  getPatientInfo()


  //3.创建订单
  const orderId= ref('')
  // 4. 自定义支付弹窗
const customPaymentRef = ref<UniHelper.UniPopupInstance>()
  const handleCreateOrder = async ()=>{
    //如果订单id存在，则不能重复创建
    if(orderId.value){
      return uni.showToast({title:'订单不能重复创建！',icon:'error'})
    }
    //创建订单
    const res = await postPatientConsultOrderAPI({
      type: Number(store.type),
      illnessType: Number(store.illnessType),
      patientId: store.patientId,
      depId: store.depId,
      illnessDesc: store.illnessInfo.illnessDesc,
      illnessTime: store.illnessInfo.illnessTime,
      consultFlag: store.illnessInfo.consultFlag,
      pictures: store.illnessInfo.pictures,
    })
    //接收订单ID
    orderId.value = res.data.id
    //将Pinia中缓存的数据清空掉（订单已创建完成）
    // store.$reset()
     // 4. 打开支付弹窗
  customPaymentRef.value?.open?.()
  }



//关闭支付弹窗
const handleClose = async ()=>{
  //二次确认提示
  const res = await uni.showModal({
    title:'关闭支付',
    content: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelText: '仍要关闭',
    cancelColor: '#848484',
    confirmText: '继续支付',
    confirmColor: '#16C2A3',
  })
  //如果用户选择关闭，则关闭支付弹窗
  if(res.cancel){
    customPaymentRef.value?.close?.()
  }
}

  //确认支付
  const handleConfirm = (index:number)=>{
    if(index===0){
      uni.showToast({title:'微信支付暂不支持',icon:'none'})
    }else if(index===1){
     const res = await postPatientConsultPayAPI({
      orderId: orderId.value,
      paymentMethod: '1',
      payCallback: 'http://localhost:5173/#/subpkg_consult/pages/room/room',
    })
    location.href = res.data.payUrl 
    }
  }

  // 切换支付方式
const handleChange = (index: number) => {
  console.log('切换支付方式', index)
}
  

</script>

<template>
  <scroll-view>
    <view class="payment-page">
      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        :title="`图文问诊 ${orderPreInfo?.payment ?? '--'} 元`"
      >
        <uni-list :border="false">
          <uni-list-item
            title="极速问诊"
            note="自动分配医生"
            thumb="/static/uploads/doctor-avatar.jpg"
            thumb-size="lg"
          />
          <uni-list-item 
          title="优惠券" 
          show-arrow 
          :right-text="`-￥${orderPreInfo?.couponDeduction ?? ''}`"           
          />
          <uni-list-item title="积分抵扣">
            <template #footer>
              <view class="uni-list-text-red">-¥{{ orderPreInfo?.pointDeduction ?? '' }}</view>
            </template>
          </uni-list-item>
          <uni-list-item title="实付款">
            <template #footer>
              <view class="uni-list-text-red">¥{{ orderPreInfo?.actualPayment ?? '' }}</view>
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>

      <view class="dividing-line"></view>

      <uni-section title-font-size="32rpx" title-color="#121826" padding="30rpx" title="患者资料">
        <uni-list :border="false">
          <uni-list-item title="患者信息">
            <template #footer>
              <view 
              class="uni-list-text-gray"
              v-if="patientInfo"
              > {{ patientInfo?.name }} |{{ patientInfo?.genderValue }} |{{ patientInfo?.age }}</view>
            </template>
          </uni-list-item>
          <uni-list-item border title="病情描述" :note="store.illnessInfo.illnessDesc" />
        </uni-list>
      </uni-section>

      <!-- <view class="payment-agreement">
        <radio color="#20c6b2" value="1" />
        我已同意<text style="color: #20c6b2">支付协议</text>
      </view> -->
    </view>
    <!-- 下一步操作 -->
    <view class="next-step">
      <view class="total-amount"> 合计: <text class="number">{{ orderPreInfo?.payment ?? '' }}</text> </view>
      <button class="uni-button"
      @click="handleCreateOrder"
      >立即支付</button>
    </view>
    <!-- 自定义支付弹窗 -->
    <custom-payment 
    ref="customPaymentRef" 
    :order-id="orderId"
    v-if="orderPreInfo?.payment"
    :amount="orderPreInfo?.payment"
    @close="handleClose"
    @confirm="handleConfirm"
    @change="handleChange"
    />
  </scroll-view>
</template>

<style lang="scss">
@import './index.scss';
</style>
